
/*
*Released on 28th June 2008.
*Any violations can be reported at paritosh@wikiocean.net
*What is treated as violations can be found at www.wikiocean.net/ppl1-voilations*
******************************************************************************
* The contents of this file are subject to POOL Public License 1.0 and later.
* POOL Public License is based on Affero GPL v3 and additional conditions.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the Affero GPL v3 License at http://www.gnu.org/licenses/agpl.html
* You may obtain a copy of the POOL Public License 1.0 or later at www.wikiocean.net/license/ppl.html
* Software distributed under POOL Public License 1.0 is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya (C) 2008. All Rights Reserved.
******************************************************************************
* Objective of the additional terms (license)
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencies.
* 3) To avoid a situation where big corporate or investor can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the freedom is curtailed in companies that get Venture Capital funding.)
******************************************************************************
*/

package  pool.preprocess;


import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Map;
import java.util.Vector;

import logger.PoolLogger;

import pool.tablename.Pool;

import utility.CapitalChar;
import utility.ConvertToLower;
import utility.Input;
import database.RecordSearch;
import dbmanager.Column;
import dbmanager.DBManager;
import dbmanager.GetIdName;


public class Validation  implements Process
{
	Object obj;
	Pool masterclass;
	String TYPE="type";
	GetIdName gid;
	String mastername;
	String MASTERNAME="mastername";
	String type;
	String VALIDATION="validation";
	String validation;
	String ISMANDARORY = "ismandatory";
	StringBuffer Error = new StringBuffer();
	public Hashtable<Object, Object> ErrorMap = new Hashtable<Object, Object>();
	public Hashtable<Object,Object> Errortable =new Hashtable<Object,Object>();
	boolean flagref;
	PoolLogger pl;
	Hashtable<Object, Object> masterhashtabel  =new Hashtable<Object, Object>();
	Hashtable<Object, Object> Basichashtabel =new Hashtable<Object, Object>();
	Vector<Object>PropertyVector =new Vector<Object>();
	
	public Validation() 
	{
		// logger
		pl = (PoolLogger) PoolLogger.getLogger(this.getClass().getName());
	}
	
	public void setObject(Object masterclasse) 
	{
		this.masterclass =(Pool)  masterclasse;
		gid = new GetIdName();
		TYPE  = gid.getId(TYPE);
		VALIDATION = gid.getId(VALIDATION);
		ISMANDARORY = gid.getId(ISMANDARORY);
		MASTERNAME = gid.getId(MASTERNAME);
	}
	
	public void setType(String type)
	{
		this.type =type;
	}
	
	public void process(String validationobject)
	{
	//String Masterpath = Input.MASTERREPORTSPATH + validationobject + "//" + validationobject + "_mid" + Input.FILRFORMAT;
	/*SearchRecord sr = new SearchRecord(Masterpath);
	sr.fileOpen();*/
	Hashtable<Object,Object> temphashtable = new Hashtable<Object,Object>();
	Hashtable<Object,Object> temptable = new Hashtable<Object,Object>();
	temphashtable.clear();
	temphashtable.put("mid", validationobject);
	/*String line[] = sr.getRecordSet(temphashtable);
	sr.fileClose();*/
	temphashtable.put("td", "null");
	RecordSearch ps = new RecordSearch();
	ps.setConditionMap(temphashtable);
	String line[] = ps.getArrayFromResultSet();	
	System.out.println("Hash Table is"+masterhashtabel);
	pl.info("Hash Table is"+masterhashtabel);
	pl.debug("Hash Table is"+masterhashtabel);
	pl.error("Hash Table is"+masterhashtabel);
	pl.trace("Hash Table is"+masterhashtabel);
	pl.fatal("Hash Table is"+masterhashtabel);
	pl.warn("Hash Table is"+masterhashtabel);
	System.out.println("Hash Table is"+PropertyVector);
	pl.info("Hash Table is"+PropertyVector);
	pl.debug("Hash Table is"+PropertyVector);
	pl.error("Hash Table is"+PropertyVector);
	pl.trace("Hash Table is"+PropertyVector);
	pl.fatal("Hash Table is"+PropertyVector);
	pl.warn("Hash Table is"+PropertyVector);
	boolean typeflag=false;
	Vector<Object> defaultproperty =new Vector<Object>();
	try 
	{
		for(int i=0;i<PropertyVector.size();i++)
		{
			if(!typeflag)
			{
				temptable.putAll((Hashtable<Object, Object>)  ConvertToLower.convertHashKey((Hashtable<Object, Object>)PropertyVector.get(i)));
				if(temptable.containsKey("pid"))
				{
					String value=temptable.get("pid").toString();
					if(value.equals(TYPE))
					{
						typeflag =true;
						break;
					}	
				}
			}
		}
	}
	catch (Exception e) 
	{
		e.printStackTrace();
	}
	
	
	for(int i=0;i<line.length;i++)
	{
			boolean flag=false;
			String splitline[] = line[i].split("\t");
			System.out.println("Validation object is"+splitline[Column.pid_index]);
			pl.info("Validation object is"+splitline[Column.pid_index]);
			pl.debug("Validation object is"+splitline[Column.pid_index]);
			pl.error("Validation object is"+splitline[Column.pid_index]);
			pl.trace("Validation object is"+splitline[Column.pid_index]);
			pl.fatal("Validation object is"+splitline[Column.pid_index]);
			pl.warn("Validation object is"+splitline[Column.pid_index]);
			String property =gid.getItem(splitline[Column.pid_index-1]).toLowerCase();
			defaultproperty.add(splitline[Column.pid_index-1]);
			if(MASTERNAME.equals((splitline[Column.pid_index-1])))
			{
				//String path = Input.MASTERREPORTSPATH + splitline[Column.pv_index-1] + "//" + splitline[Column.pv_index-1] + "_mid" + Input.FILRFORMAT;
				String actualvalue = masterhashtabel.get("name").toString();
				//sr = new SearchRecord(path);
				temphashtable.clear();
				temphashtable.put("mid", splitline[Column.pv_index-1]);
				/*sr.fileOpen();
				String result[] = sr.getRecordSet(temphashtable);
				sr.fileClose();*/
				temphashtable.put("td", "null");
				ps = new RecordSearch();
				ps.setConditionMap(temphashtable);
				String result[] = ps.getArrayFromResultSet();
				loadvalidationobject(result, actualvalue, splitline[Column.pid_index-1],"");
				flag = true;
			}
			 if(masterhashtabel.containsKey(property))
			{
			try {
				//	String path = Input.MASTERREPORTSPATH + splitline[Column.pv_index-1] + "//" + splitline[Column.pv_index-1] + "_mid" + Input.FILRFORMAT;
					String actualvalue =masterhashtabel.get(property).toString();
					String basicvalue = Basichashtabel.get(property).toString();
					/*sr.fileOpen();
					sr = new SearchRecord(path);*/
					temphashtable.clear();
					temphashtable.put("mid", splitline[Column.pv_index-1]);
					/*String result[] = sr.getRecordSet(temphashtable);
					sr.fileClose();*/
					temphashtable.put("td", "null");
					ps = new RecordSearch();
					ps.setConditionMap(temphashtable);
					String result[] = ps.getArrayFromResultSet();
					/*if(splitline[Column.pid_index-1].equalsIgnoreCase("pid"))
					try 
					{
						if(actualvalue.equals("0"))
							actualvalue = temptable.get("vt").toString();
						else
							actualvalue = gid.getItem(actualvalue);
					}
					catch (Exception e1) 
					{
						e1.printStackTrace();
					}*/
					loadvalidationobject(result, actualvalue, splitline[Column.pid_index-1],basicvalue);
					try 
					{
						if(splitline[Column.ref_index-1].equals("0")==true||splitline[Column.ref_index-1].equals("no$")==true);
						else
						{
							//String refpath = Input.MASTERREPORTSPATH + splitline[Column.pv_index-1] + "//" + splitline[Column.ref_index-1] + "_mid" + Input.FILRFORMAT;
							String refactualvalue = masterhashtabel.get(splitline[Column.ref_index-1]).toString();
							//sr = new SearchRecord(refpath);
							temphashtable.clear();
							temphashtable.put("mid", splitline[Column.ref_index-1]);
							//String refresult[] = sr.getRecordSet(temphashtable);
							temphashtable.put("td", "null");
							ps.setConditionMap(temphashtable);
							String refresult[] = ps.getArrayFromResultSet();
							if(refactualvalue.equals("0"))
								refactualvalue = temptable.get("vt").toString();
							else
								refactualvalue = gid.getItem(actualvalue);
							flagref = true;
							loadvalidationobject(refresult, refactualvalue, splitline[Column.ref_index-1],"");
						}
					}
					catch (Exception e) 
					{
						e.printStackTrace();
					}
					flag = true;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			}
			try 
			{
				for(int j=0;j<PropertyVector.size();j++)
				{
					try {
						temptable.clear();
						temptable.putAll((Hashtable<Object, Object>)  ConvertToLower.convertHashKey((Hashtable<Object, Object>)PropertyVector.get(j)));
						System.out.println("Hash Table is "+temptable);
						pl.info("Hash Table is "+temptable);
						pl.debug("Hash Table is "+temptable);
						pl.error("Hash Table is "+temptable);
						pl.trace("Hash Table is "+temptable);
						pl.fatal("Hash Table is "+temptable);
						pl.warn("Hash Table is "+temptable);
						if(temptable.get("pid").equals((splitline[Column.pid_index-1])))
						{
							String path = Input.MASTERREPORTSPATH + splitline[Column.pv_index-1] + "//" + splitline[Column.pv_index-1] + "_mid" + Input.FILRFORMAT;
							String actualvalue = temptable.get("pv").toString();
							if(actualvalue.equals("0"))
								actualvalue = temptable.get("vt").toString();
							else
								actualvalue = gid.getItem(actualvalue);
							//sr = new SearchRecord(path);
							temphashtable.clear();
							temphashtable.put("mid", splitline[Column.pv_index-1]);
							//String result[] = sr.getRecordSet(temphashtable);
							temphashtable.put("td", "null");
							ps = new RecordSearch();
							ps.setConditionMap(temphashtable);
							String result[] = ps.getArrayFromResultSet();
							loadvalidationobject(result, actualvalue, splitline[Column.pid_index-1],"");
							if(splitline[Column.ref_index-1].equals("0")==true||splitline[Column.ref_index-1].equals("no$")==true);
							else
							{
								String refpath = Input.MASTERREPORTSPATH + splitline[Column.ref_index-1] + "//" + splitline[Column.ref_index-1] + "_mid" + Input.FILRFORMAT;
								//sr = new SearchRecord(refpath);
								Hashtable<Object, Object > newhashtable = new  Hashtable<Object, Object>();
								newhashtable.put("mid", splitline[Column.ref_index-1]);
								//String refresult[] = sr.getRecordSet(newhashtable);
								temphashtable.put("td", "null");
								ps = new RecordSearch();
								ps.setConditionMap(newhashtable);
								String refresult[] = ps.getArrayFromResultSet();
								String refactualvalue = temptable.get("ref").toString();
								refactualvalue = gid.getItem(refactualvalue);
								flagref = true;
								loadvalidationobject(refresult, refactualvalue, splitline[Column.pid_index-1],"");
								flagref =false;
							}
							flag = true;
						}
					} catch (Exception e) 
					{
						e.printStackTrace();
					}
				}
			}
			catch (Exception e) 
			{
				e.printStackTrace();
			}			
			if(flag==false && typeflag == true)
			{
				flag = true;
				String actualvalue = temptable.get("pv").toString();
				if(actualvalue.equals("0"))
					actualvalue = temptable.get("vt").toString();
				else
					actualvalue = gid.getItem(actualvalue);	
				//sr = new SearchRecord(path);
				temphashtable.clear();
				temphashtable.put("mid", splitline[Column.pv_index-1]);
				temphashtable.put("pid", ISMANDARORY);
				temphashtable.put("td", "null");
				//String result[] = sr.getRecordSet(temphashtable);
				
				ps = new RecordSearch();
				ps.setConditionMap(temphashtable);
				String result[] = ps.getArrayFromResultSet();
				loadvalidationobject(result , actualvalue, splitline[Column.pid_index-1],"");
				try 
				{
					if(!splitline[Column.ref_index-1].equals("0"))
					{
						String refpath = Input.MASTERREPORTSPATH + splitline[Column.ref_index-1] + "//" + splitline[Column.ref_index-1] + "_mid" + Input.FILRFORMAT;
						String refactualvalue ="";
						try 
						{
							refactualvalue = temptable.get("ref").toString();
						}
						catch (Exception e) 
						{
						}
						//sr = new SearchRecord(refpath);
						temphashtable.clear();
						temphashtable.put("mid", splitline[Column.ref_index-1]);
						//String refresult[] = sr.getRecordSet(temphashtable);
						temphashtable.put("td", "null");
						ps = new RecordSearch();
						ps.setConditionMap(temphashtable);
						String refresult[] = ps.getArrayFromResultSet();
						//refactualvalue = gid.getItem(actualvalue);
						refactualvalue = actualvalue;					
						loadvalidationobject(refresult, refactualvalue, splitline[Column.pv_index-1],"");
					}
				}
				catch (Exception e) 
				{
					e.printStackTrace();
				}
			}	
		}
	try 
	{
		for(int i=0;i<PropertyVector.size();i++)
		{	
			temptable.putAll((Hashtable<Object, Object>)  ConvertToLower.convertHashKey((Hashtable<Object, Object>)PropertyVector.get(i)));
			if(!defaultproperty.contains(temptable.get("pid")))
			{
				Error.append(gid.getItem(temptable.get("pid").toString())+" is not valid property,");
			}
		}
	}
	catch (Exception e) 
	{
		e.printStackTrace();
	}
	Enumeration<Object> masterenum = masterhashtabel.keys();
	/*while(masterenum.hasMoreElements())
	{
		String key = masterenum.nextElement().toString();
		String Masterkey = gid.getId(key);
		if(Masterkey.equals("no$") || Masterkey.equals("0"))
			Masterkey = key;
		if(!defaultproperty.contains(Masterkey))
		{
			key = gid.getId(Masterkey);
			if(key.equals("no$") || key.equals("0"))
				key = Masterkey;
			Error.append(key+" is not valid property,");
		}
	}*/
	if(Error.length()!=0)
		{
			ErrorMap.put("Errorvalidation",Error);
			Errortable.clear();
			Errortable.put("ErrorInput",ErrorMap);
		}
	}
	public Object getObject() 
	{
		 masterhashtabel = ConvertToLower.convertHashKey(masterclass.getHashtabel());
		 Basichashtabel =ConvertToLower.convertHashKey(masterclass.getBasicHashtable());
		PropertyVector = masterclass.getpropertyVector();
		
			return this;
	}
	
	@SuppressWarnings("unchecked")
	public void loadvalidationobject(String [] line,String actualvalue,String pvvalue,String basicvalue)
	{	
		for(int k=0;k<line.length;k++)
		{	
		String Splitline[]=line[k].split("\t");
		String validationobj = Splitline[Column.pid_index-1];
		String validationvalue = Splitline[Column.pv_index-1];
	     if(validationvalue.equals("0"))
	    	 validationvalue = Splitline[Column.vt_index-1];
	     else
	    	 validationvalue = gid.getItem(validationvalue);
	     String Refvalue;
		try
		{
			Refvalue = Splitline[Column.ref_index-1];
		}
		catch (Exception e1) 
		{
			Refvalue = "";
		}
	     validation.Validation errorvalidation;
	     try 
	     {
    	    Class C = Class.forName("validation."+CapitalChar.makeFirstCharCapital(gid.getItem(validationobj)));
			errorvalidation = (validation.Validation )C.newInstance();
			errorvalidation.initPool();
			errorvalidation.setBasicvalue(basicvalue);
			if(!errorvalidation.validate(actualvalue,validationvalue,Refvalue))
			{
				String MasterName = gid.getItem(pvvalue);
				if(flagref)
				Error.append("ref value of "+MasterName+" " +errorvalidation.getMessage() + ", ");
				else
				Error.append(MasterName+" " +errorvalidation.getMessage() + ", ");
				
			}
		 } 
	     catch (ClassNotFoundException e) 
	     {
		 }
	     catch (InstantiationException e) 
	     {
			e.printStackTrace();
		 } 
	     catch (Exception e) 
	     {
			e.printStackTrace();
		}
	     
	}
	
  }
	public Hashtable<Object, Object> gethashtable() 
	{	
		return Errortable;
	}

	public void setType(String type, String table) 
	{
		this.type =type;
	}

	
	public void beforeAdd(String value)
	{
		process(value);		
	}

	public void beforeDel(String value) 
	{
		process(value);		
	}

	public void beforeMod(String value) 
	{
		process(value);		
	}

	
	public void beforeView(String value) 
	{
		process(value);
		
	}


	public Hashtable<Object, Object> getMasterMap()
	{
		return masterhashtabel;
	}


	public Vector<Object> getPropertyVector() 
	{
		return PropertyVector;
	}


	public void setBasicMap(Hashtable<Object, Object> Mastermap) 
	{
		this.Basichashtabel.putAll(Mastermap);
		
	}


	public void setMasterMap(Hashtable<Object, Object> Mastermap) 
	{
		this.masterhashtabel.putAll(Mastermap);
	}


	public void setPropertyvector(Vector<Object> PropertyVector) 
	{
		this.PropertyVector.addAll(PropertyVector);
	}		
}
	
	
		
	
	
	
	